<?php

namespace app\data\controller;

use app\data\model\OwnerShareInfoModel;
use Exception;
use think\admin\Controller;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use Vtiful\Kernel\Excel;

class OwnerShare extends Controller
{
    /**
     * 当前操作数据库
     * @var string
     */
    private string $table = 'OwnerShare';

    /**
     * 业主关联数据管理
     * @auth true
     * @menu true
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function index()
    {
        $this->title = '业主关联数据管理';

        $this->_query(OwnerShareInfoModel::class)->like('name,tel, id_card')->equal('region,build,unit,floor,house')->page(true, true);
    }

    /**
     * 导入数据
     * @auth true
     * @return void
     * @throws Exception
     */
    public function import()
    {
        $file = $this->app->request->post('file');
        if (!$file) $this->error('文件不能为空');

        $config = ['path' => './upload'];

        $excel = new Excel($config);

        $data = $excel->openFile($file)
            ->openSheet()
            ->getSheetData();

        $cellName = $data[0];

        unset($data[0]);
        $result = [];
        $time = time();
        foreach ($data as $item) {
            $res = [];
            foreach ($cellName as $k => $v) {
                $res[$v] = $item[$k];
                $res['create_time'] = $res['update_time'] = $time;
            }
            $result[] = $res;
        }
        if ($result != []) {
            $model = new OwnerShareInfoModel();
            $model->insertAll($result);
            $this->success('数据导入成功');
        } else {
            $this->error('数据为空');
        }
    }

    /**
     * @return void
     */
    public function add()
    {
        OwnerShareInfoModel::mForm('form');
    }

    /**
     * @return void
     */
    public function edit()
    {
        OwnerShareInfoModel::mForm('form');
    }

    /**
     * 删除系统用户
     * @auth true
     */
    public function remove()
    {
        OwnerShareInfoModel::mDelete();
    }
}